package com.cxf.windex.task;

import com.cxf.windex.base.bean.LockInfo;
import com.cxf.windex.base.constant.LockConstant;
import com.cxf.windex.base.constant.UserConstant;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.biz.ActivityBiz;
import com.cxf.windex.biz.BOrdersBiz;
import com.cxf.windex.biz.MoneyBiz;
import com.cxf.windex.biz.MoneyLogBiz;
import com.cxf.windex.entity.Activity;
import com.cxf.windex.entity.Money;
import com.cxf.windex.entity.MoneyLog;
import com.cxf.windex.enums.ActivityEnum;
import com.cxf.windex.enums.BonusTypeEnum;
import com.cxf.windex.enums.OperateEnum;
import java.math.BigDecimal;
import java.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

/**
 * @program: business_needs
 * @description:
 * @author: chenxf
 * @create: 2018-11-01 11:44
 **/
@Slf4j
@Component
public class LogTask {
  @Autowired
  private MoneyBiz moneyBiz;
  @Autowired
  private MoneyLogBiz moneyLogBiz;
  @Autowired
  private ActivityBiz activityBiz;
  @Autowired
  private BOrdersBiz bOrdersBiz;

  @Async
  public void payMoney(String openid,BigDecimal payMoney,OperateEnum operateEnum,String range,String bindId){
    payMoney(openid,payMoney,operateEnum,range,bindId, false);
  }

  /**
   *
   * @param openid 用户openid
   * @param payMoney 支付金额
   * @param operateEnum 支付操作
   * @param range  用户类型 0商家 1村长
   * @param bindId  绑定相关操作
   * @param isCost  true 余额  false 佣金
   */
  @Async
  public void payMoney(String openid,BigDecimal payMoney,OperateEnum operateEnum,String range,String bindId,boolean isCost){
    LockInfo lockInfo = new LockInfo(LockConstant.MONEY_LOCK+openid);
    try {
      Money money=moneyBiz.getInfo(openid);
      if(isCost){
        money.setCost(money.getCost().add(payMoney));
      }else {
        money.setIncome(money.getIncome().add(payMoney));
      }
      doQbzz(money,operateEnum,operateEnum.getDesc(),payMoney.toString(),range,bindId);
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      lockInfo.unlock();
    }
  }

  //@Async
  public Future<String> doQbzz(Money money,OperateEnum opreate,String notes,String zcCount,String range,String bindId)  {
    //用户资金锁

      long start = System.currentTimeMillis();
      moneyBiz.updateSelectiveById(money);
      this.accountLog(money.getName(),money.getWxopenid(),opreate,notes,zcCount,range,bindId);
      long end = System.currentTimeMillis();
      log.debug("钱包操作：" + (end - start) + "毫秒");

    return new AsyncResult<>("资金记录完成");
  }

  /**
   * 生成资金记录
   * @param name   用户NAME
   * @param userid  用户ID
   * @param opreate  操作
   * @param notes    备注
   * @param zcCount  消耗金额
   * @param range  0 商家 1资源
   * @param bindId 关联ID
   */
  public void accountLog(String name,String userid,OperateEnum opreate,String notes,String zcCount,String range,String bindId){
    MoneyLog entity=new MoneyLog();
    entity.setId(UserConstant.LOG_ID_PREX+new IdUtil(5,1).nextId());
    if(opreate.getKey().startsWith("s")  ){
      entity.setMoney(new BigDecimal(0).subtract(new BigDecimal(zcCount)));
    }else{
      entity.setMoney(new BigDecimal(zcCount));
    }
    entity.setTypeName(opreate.getDesc());
    entity.setType(opreate.getKey());
    entity.setName(name);
    entity.setNotes(notes);
    entity.setWxopenid(userid);
    entity.setBindId(bindId);
    if(opreate.getKey().contains("froze")){
      //设置提现申请未处理状态
      entity.setStatus("0");
    }else{
      entity.setStatus("1");
    }
    moneyLogBiz.insertSelective(entity);

    //生成活动奖励
    activityLog(userid,opreate,zcCount,range);
    orderSuc(bindId,opreate,zcCount);

  }

  private void orderSuc(String orderId,OperateEnum opreate,String zcCount){
    if( "s_cost_orders".equals(opreate.getKey())){
      //设置订单状态为已支付
      bOrdersBiz.suc(orderId,zcCount);
    }
    if( "s_wx_orders".equals(opreate.getKey())){
      //设置订单状态为已支付
      bOrdersBiz.suc(orderId,zcCount);
    }
    if( "s_income_orders".equals(opreate.getKey())){
      //设置订单状态为已支付
      bOrdersBiz.suc(orderId,zcCount);
    }
  }
  /**
   * 生成活动奖励
   * @param userid 用户ID
   * @param opreate 操作
   * @param zcCount 金额
   * @param range 终端 0商家 1资源
   */
  private void activityLog(String userid,OperateEnum opreate,String zcCount,String range){
    if(StringUtils.isBlank(range)){
      return;
    }
    Activity activity=null;
    BigDecimal activityMoney=BigDecimal.ZERO;
    LockInfo lockInfo = new LockInfo(LockConstant.MONEY_LOCK+userid);
    try {
      //认证有活动
      if(opreate.getKey().equals("s_wx_cert")){
        activity=activityBiz.queryActivity(range,ActivityEnum.CERT,new BigDecimal(zcCount));
        activityMoney=BonusTypeEnum.keyOf(activity.getBonusType()).cumputer(new BigDecimal(zcCount),activity.getMoney(),activity.getBonus());
        Money money=moneyBiz.getInfo(userid);
        money.setCost(money.getCost().add(activityMoney));
        this.doQbzz(money,OperateEnum.COST_ACTIVITY,activity.getName()+"奖励 "+activityMoney.toString()+" 元",activityMoney.toString(),range,activity.getId());
      }
    } catch (Exception e) {
      e.printStackTrace();
       log.error("钱包操作失败 e={}",e.getMessage());
    }finally {
      lockInfo.unlock();
    }
  }
}
